<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useContainerStore } from '../stores/containerStore'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { saveToAPI, getFromAPI, STORAGE_KEYS ,API_BASE_URL } from '../utils/storage'
import { Timer, Clock, Check, ArrowLeft, Plus } from '@element-plus/icons-vue'
import { endContainerApi, uploadContainerEvidence } from '../api/container'


const router = useRouter()

const containerStore = useContainerStore()

// 表单数据
const containerForm = ref({
  title: '',
  description: '',
  category: '',
  estimatedTime: 30, // 默认30分钟
  tags: [], // 标签
  relatedPostId: '', // 关联的帖子ID
  relatedReplyId: '' // 关联的回复ID
})

// 表单规则
const rules = {
  title: [{ required: true, message: '请输入容器名称', trigger: 'blur' }],
  estimatedTime: [{ required: true, message: '请输入预估时间', trigger: 'blur' }]
}

// 表单引用
const formRef = ref(null)

// 选择历史容器对话框
const showHistoryDialog = ref(false)

// 历史容器搜索关键词
const historySearchKeyword = ref('')

// 分类选项
const categoryOptions = [
  { label: '工作', value: '工作' },
  { label: '学习', value: '学习' },
  { label: '阅读', value: '阅读' },
  { label: '写作', value: '写作' },
  { label: '思考', value: '思考' },
  { label: '运动', value: '运动' },
  { label: '其他', value: '其他' }
]

// 当前活动的容器
const activeContainer = computed(() => containerStore.activeContainer)

// 检查是否有返回信息
const hasReturnInfo = computed(() => {
  return sessionStorage.getItem('returnTo') && sessionStorage.getItem('returnPlanId')
})

// 已完成的容器列表（用于选择模板）
const completedContainers = computed(() => {
  return containerStore.completedContainers.filter(container => {
    if (!historySearchKeyword.value) return true
    const keyword = historySearchKeyword.value.toLowerCase()
    return container.title.toLowerCase().includes(keyword) ||
           (container.description && container.description.toLowerCase().includes(keyword)) ||
           (container.category && container.category.toLowerCase().includes(keyword))
  })
})

// 计时器
let timer = null
const elapsedTime = ref(0)

// 开始新容器
function startContainer() {
  formRef.value.validate((valid) => {
    if (valid) {
      containerStore.createContainer(containerForm.value)
      startTimer()
      // AI添加：创建容器后立即保存容器数据
      const saveNewContainerData = async () => {
        try {
          // 获取刚创建的活动容器
          const newContainer = containerStore.activeContainer
          if (!newContainer) throw new Error('未找到新建的容器')
          const containerData = {
            id: newContainer.id,
            title: newContainer.title,
            description: newContainer.description || '', // AI添加：保存描述
            category: newContainer.category || '', // AI添加：保存分类
            elapsedTime: 0,
            // tags: Array.isArray(newContainer.tags) ? newContainer.tags : [], // AI添加：保存标签
            // startTime: newContainer.startTime || new Date().toISOString() 后端自己new
          }
          const isSaved = await saveToAPI(STORAGE_KEYS.CONTAINERS, containerData)
          if (!isSaved) {
            throw new Error('保存新建容器数据失败')
          }
          console.log('新建容器数据保存成功')
        } catch (error) {
          console.error('保存新建容器数据时出错:', error)
          // 可选：添加用户提示
        }
      }
      saveNewContainerData()
      // 重置表单
      containerForm.value = {
        title: '',
        description: '',
        category: '',
        estimatedTime: 30,
        tags: [],
        relatedPostId: '',
        relatedReplyId: ''
      }
      
      // 检查是否需要返回到计划详情页
      handleReturnToPlan()
    }
  })
}

// 取消返回，直接返回计划详情页
function cancelReturn() {
  const returnTo = sessionStorage.getItem('returnTo')
  const planId = sessionStorage.getItem('returnPlanId')
  
  if (returnTo && planId) {
    sessionStorage.removeItem('returnTo')
    sessionStorage.removeItem('returnPlanId')
    
    router.push({
      path: returnTo,
      query: { id: planId }
    })
  }
}

// 处理返回到计划详情页的逻辑
function handleReturnToPlan() {
  const returnTo = sessionStorage.getItem('returnTo')
  const planId = sessionStorage.getItem('returnPlanId')
  
  if (returnTo && planId) {
    // 清理sessionStorage
    sessionStorage.removeItem('returnTo')
    sessionStorage.removeItem('returnPlanId')
    
    // 返回计划详情页
    router.push({
      path: returnTo,
      query: { id: planId }
    })
    
    ElMessage.success('容器创建成功，已返回计划详情页')
  }
}

// 结束当前容器对话框
const endContainerDialogVisible = ref(false)

// 结束证据上传相关
const evidenceFile = ref(null)
const evidenceFileList = ref([])

function handleEvidenceChange(file, files) {
  // 仅保留最新选择的一个文件
  evidenceFileList.value = files.slice(-1)
  evidenceFile.value = files.length ? (files[files.length - 1].raw || files[files.length - 1]) : null
}

function handleEvidenceRemove() {
  evidenceFile.value = null
  evidenceFileList.value = []
}

// 结束当前容器
function endCurrentContainer() {
  if (activeContainer.value) {
    endContainerDialogVisible.value = true
  }
}

// 返回关联的社区帖子
function backToRelatedPost() {
  if (activeContainer.value && activeContainer.value.relatedPostId) {
    router.push(`/campfire/post/${activeContainer.value.relatedPostId}`)
  }
}

// 确认结束容器
async function confirmEndContainer(createArchive) {
  stopTimer()
  endContainerDialogVisible.value = false

  try {
    const containerId = activeContainer.value.id
    // 先结束容器
    await endContainerApi(Number(containerId))
    // 若选择了证据图片，则上传
    if (evidenceFile.value) {
      await uploadContainerEvidence(Number(containerId), evidenceFile.value)
    }
    ElMessage.success('容器已结束' + (evidenceFile.value ? '，证据已上传' : ''))
  } catch (error) {
    ElMessage.error('结束容器失败：' + (error?.message || '未知错误'))
    return
  }

  if (createArchive) {
    router.push({
      path: '/mind-archive',
      query: {
        containerId: activeContainer.value.id,
        containerTitle: activeContainer.value.title,
        containerDescription: activeContainer.value.description,
        containerCategory: activeContainer.value.category
      }
    })
  } else {
    router.push('/evaluation')
  }
}

// 开始计时器
function startTimer() {
  if (timer) clearInterval(timer)
  elapsedTime.value = 0
  timer = setInterval(() => {
    elapsedTime.value++
  }, 1000)
}

// 停止计时器
function stopTimer() {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}

// 格式化时间
function formatTime(seconds) {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 计算剩余时间百分比
const remainingPercentage = computed(() => {
  if (!activeContainer.value) return 100
  
  const estimatedSeconds = activeContainer.value.estimatedTime * 60
  const elapsed = elapsedTime.value
  
  return Math.max(0, Math.min(100, ((estimatedSeconds - elapsed) / estimatedSeconds) * 100))
})

// 计算剩余时间状态
const timeStatus = computed(() => {
  if (!activeContainer.value) return 'normal'
  
  const estimatedSeconds = activeContainer.value.estimatedTime * 60
  const elapsed = elapsedTime.value
  
  if (elapsed > estimatedSeconds) return 'danger'
  if (elapsed > estimatedSeconds * 0.8) return 'warning'
  return 'normal'
})

// 组件挂载时检查是否有活动容器
onMounted(async () => {
  // 初始化容器数据
  await containerStore.initFromAPI()
  
  // 检查URL参数是否有自动开始容器的请求
  const { id, autoStart, returnTo, planId } = router.currentRoute.value.query
  
  // 如果有returnTo参数，保存返回信息
  if (returnTo && planId) {
    sessionStorage.setItem('returnTo', returnTo)
    sessionStorage.setItem('returnPlanId', planId)
  }
  
  if (activeContainer.value) {
    // 计算已经过去的时间
    const startTime = dayjs(activeContainer.value.startTime)
    const now = dayjs()
    const diffSeconds = now.diff(startTime, 'second')
    
    elapsedTime.value = diffSeconds
    startTimer()
  } else if (id && autoStart === 'true') {
    // AI 调整：从数据库查询指定ID的容器
    try {
      // 调用 getFromAPI 查询容器数据
      const container = await getFromAPI(`containers/${id}`);
      if (container && !container.endTime) {
        containerStore.setActiveContainer(container);
        startTimer();
      }
    } catch (error) {
      console.error('查询容器数据失败:', error);
      // TODO: 可以在这里添加用户提示逻辑（如弹窗提示）
    }
  }

  // 可能未掌握的知识点：
  // 1. async/await：异步操作需要 async 函数和 await 关键字配合使用。
  // 2. Error Handling：try/catch 块用于捕获异步操作中的错误。
  // 3. API 调用：getFromAPI 是异步函数，必须用 await 或 .then() 处理。
})

// 组件卸载时清除计时器
onUnmounted(() => {
  stopTimer()
})

// 打开历史容器选择对话框
function openHistoryDialog() {
  showHistoryDialog.value = true
  historySearchKeyword.value = ''
}

// 选择历史容器作为模板
function selectHistoryContainer(container) {
  // 填充表单数据（保持原有ID和时间信息）
  containerForm.value = {
    title: container.title + ' (复用)', // 添加复用标记
    description: container.description || '',
    category: container.category || '',
    estimatedTime: container.estimatedTime || 30,
    tags: container.tags || [],
    relatedPostId: '', // 清空关联帖子
    relatedReplyId: '' // 清空关联回复
  }
  
  showHistoryDialog.value = false
  ElMessage.success(`已使用容器“${container.title}”作为模板`)
}

// 格式化时间显示
function formatDateTime(dateTimeStr) {
  if (!dateTimeStr) return ''
  return dayjs(dateTimeStr).format('MM-DD HH:mm')
}

// 获取容器效果评分显示
function getEffectivenessDisplay(container) {
  if (container.evaluation && container.evaluation.effectivenessScore) {
    const score = container.evaluation.effectivenessScore
    const stars = '★'.repeat(score) + '☆'.repeat(5 - score)
    return `${stars} (${score}/5)`
  }
  return '未评价'
}
</script>

<template>
  <div class="container-view">
    <h1>时间容器</h1>
    
    <!-- 活动容器 -->
    <div v-if="activeContainer" class="active-container">
      <el-card class="container-card">
        <template #header>
          <div class="card-header">
            <h2>{{ activeContainer.title }}</h2>
            <el-tag>{{ activeContainer.category }}</el-tag>
          </div>
        </template>
        
        <p v-if="activeContainer.description">{{ activeContainer.description }}</p>
        
        <div class="timer-section">
          <div class="timer-display">
            <span class="elapsed-time">{{ formatTime(elapsedTime) }}</span>
            <span class="estimated-time">预估: {{ activeContainer.estimatedTime }}分钟</span>
          </div>
          
          <el-progress 
            :percentage="remainingPercentage" 
            :status="timeStatus"
            :stroke-width="15"
            :show-text="false"
          />
        </div>
        
        <div class="container-actions">
          <el-button type="danger" @click="endCurrentContainer">结束容器</el-button>
          <el-button 
            v-if="activeContainer.relatedPostId" 
            type="primary" 
            plain 
            @click="backToRelatedPost"
          >
            返回社区帖子
          </el-button>
        </div>
        
        <!-- 结束容器对话框 -->
        <el-dialog
          v-model="endContainerDialogVisible"
          title="结束容器"
          width="30%"
          center
        >
          <div class="end-container-content">
            <p>是否需要创建思维存档？另外可上传一张图片作为结束证据（可选）。</p>
            <el-upload
              class="evidence-uploader"
              :file-list="evidenceFileList"
              :auto-upload="false"
              :limit="1"
              accept="image/*"
              list-type="picture-card"
              @change="handleEvidenceChange"
              @remove="handleEvidenceRemove"
            >
              <el-icon><Plus /></el-icon>
              <template #tip>
                <div class="el-upload__tip">仅支持单张图片，大小请控制在合理范围内。</div>
              </template>
            </el-upload>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="confirmEndContainer(false)">直接结束</el-button>
              <el-button type="primary" @click="confirmEndContainer(true)">
                创建思维存档
              </el-button>
            </span>
          </template>
        </el-dialog>
      </el-card>
    </div>
    
    <!-- 创建新容器 -->
    <div v-else class="create-container">
      <el-card>
        <template #header>
          <div class="create-header">
            <div class="header-left">
              <el-button 
                v-if="hasReturnInfo" 
                @click="cancelReturn" 
                size="small"
              >
                <el-icon><ArrowLeft /></el-icon>
                返回计划
              </el-button>
              <h2>创建新容器</h2>
            </div>
            <el-button 
              type="primary" 
              plain 
              @click="openHistoryDialog"
              :disabled="completedContainers.length === 0"
            >
              <el-icon><Clock /></el-icon>
              从历史容器选择
            </el-button>
          </div>
        </template>
        
        <el-form 
          ref="formRef"
          :model="containerForm" 
          :rules="rules"
          label-position="top"
        >
          <el-form-item label="容器名称" prop="title">
            <el-input v-model="containerForm.title" placeholder="例如：编写项目文档" />
          </el-form-item>
          
          <el-form-item label="分类" prop="category">
            <el-select v-model="containerForm.category" placeholder="选择分类" style="width: 100%">
              <el-option 
                v-for="option in categoryOptions" 
                :key="option.value" 
                :label="option.label" 
                :value="option.value" 
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="描述（可选）" prop="description">
            <el-input 
              v-model="containerForm.description" 
              type="textarea" 
              placeholder="简要描述你要做什么" 
              :rows="3" 
            />
          </el-form-item>
          
          <el-form-item label="预估时间（分钟）" prop="estimatedTime">
            <el-input-number 
              v-model="containerForm.estimatedTime" 
              :min="5" 
              :max="480" 
              :step="5" 
              style="width: 100%" 
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="startContainer" style="width: 100%">
              开始专注
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <!-- 历史容器选择对话框 -->
    <el-dialog
      v-model="showHistoryDialog"
      title="选择历史容器作为模板"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="history-container-dialog">
        <!-- 搜索框 -->
        <el-input
          v-model="historySearchKeyword"
          placeholder="搜索容器名称、描述或分类..."
          prefix-icon="Search"
          clearable
          class="search-input"
        />
        
        <!-- 容器列表 -->
        <div v-if="completedContainers.length === 0" class="empty-state">
          <el-empty description="暂无已完成的容器">
            <p>完成一些容器后，就可以在这里选择它们作为模板了。</p>
          </el-empty>
        </div>
        
        <div v-else class="history-list">
          <div 
            v-for="container in completedContainers" 
            :key="container.id"
            class="history-item"
            @click="selectHistoryContainer(container)"
          >
            <div class="history-item-header">
              <div class="title-section">
                <h4>{{ container.title }}</h4>
                <el-tag 
                  v-if="container.category" 
                  size="small" 
                  type="info"
                >
                  {{ container.category }}
                </el-tag>
              </div>
              <div class="meta-section">
                <span class="time-info">
                  {{ formatDateTime(container.endTime) }}
                </span>
                <span class="effectiveness">
                  {{ getEffectivenessDisplay(container) }}
                </span>
              </div>
            </div>
            
            <div class="history-item-content">
              <p v-if="container.description" class="description">
                {{ container.description }}
              </p>
              
              <div class="stats">
                <span class="stat-item">
                  <el-icon><Timer /></el-icon>
                  预估: {{ container.estimatedTime }}分钟
                </span>
                <span class="stat-item" v-if="container.actualTime">
                  <el-icon><Clock /></el-icon>
                  实际: {{ container.actualTime }}分钟
                </span>
                <span class="stat-item" v-if="container.evaluation && container.evaluation.positiveTags">
                  <el-icon><Check /></el-icon>
                  {{ container.evaluation.positiveTags.slice(0, 2).join(', ') }}
                  <span v-if="container.evaluation.positiveTags.length > 2">等</span>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showHistoryDialog = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.container-view {
  max-width: 800px;
  margin: 0 auto;
}

.container-view h1 {
  margin-bottom: 30px;
  text-align: center;
  color: #303133;
}

.active-container {
  margin-bottom: 30px;
}

.container-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 1.5rem;
}

.timer-section {
  margin: 30px 0;
}

.timer-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.elapsed-time {
  font-size: 2rem;
  font-weight: bold;
  font-family: monospace;
}

.estimated-time {
  color: #909399;
}

.container-actions {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.create-container {
  max-width: 600px;
  margin: 0 auto;
}

.create-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-left h2 {
  margin: 0;
}

.create-header h2 {
  margin: 0;
}

/* 历史容器选择对话框样式 */
.history-container-dialog {
  max-height: 500px;
}

.search-input {
  margin-bottom: 20px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.history-list {
  max-height: 400px;
  overflow-y: auto;
}

.history-item {
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fff;
}

.history-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  transform: translateY(-1px);
}

.history-item:last-child {
  margin-bottom: 0;
}

.history-item-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.title-section {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.title-section h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.meta-section {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 5px;
}

.time-info {
  font-size: 12px;
  color: #909399;
}

.effectiveness {
  font-size: 11px;
  color: #67c23a;
  font-weight: 500;
}

.history-item-content {
  margin-top: 10px;
}

.description {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.stats {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 10px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.stat-item .el-icon {
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .create-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
  
  .history-item-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .meta-section {
    align-items: flex-start;
    width: 100%;
  }
  
  .stats {
    flex-direction: column;
    gap: 8px;
  }
}
</style>